package mapx

import "gitee.com/zhongguo168a/gocodes/datax"

// 输出指定字段
func ExportField(source, fieldMap datax.M) (r datax.M) {
	r = datax.M{}
	toMapByField(source, fieldMap, r)
	return r
}

func toMapByField(data, fieldMap datax.M, r datax.M) {
	if fieldMap == nil {
		fieldMap = datax.M{}
		for key := range data {
			fieldMap[key] = nil
		}
	}
	for field, fieldValue := range fieldMap {
		dataVal := data[field]
		switch v := dataVal.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				r[field] = tm
				if fieldValue == nil {
					Copy(v, tm)
				} else {
					toMapByField(v, fieldValue.(datax.M), tm)
				}
			} else {
				r[field] = nil
			}
		default:
			r[field] = v
		}
	}
	return
}
func toMapByData(data, fieldMap datax.M, r datax.M) {
	for field, fieldValue := range fieldMap {
		dataVal := data[field]
		switch v := dataVal.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				r[field] = tm
				if fieldValue == nil {
				} else {
					toMapByField(v, fieldValue.(datax.M), tm)
				}
			} else {
				r[field] = nil
			}
		default:
			r[field] = v
		}
	}
	return
}
